<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-4xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Badging API</h1>
        <p class="text-gray-300 text-lg">
          在应用图标上显示徽章数字，用于通知用户未读消息或待处理任务
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300 mb-4">
          您的浏览器不支持 Badging API。此功能需要 Chrome 81+ 或其他支持的浏览器。
        </p>
        <p class="text-gray-400 text-sm">
          注意：此 API 主要在 PWA（渐进式Web应用）中使用，需要应用被安装到桌面。
        </p>
      </div>

      <!-- 徽章控制区域 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">徽章控制</h2>
        
        <div class="bg-gray-800 rounded-lg p-6 mb-6">
          <!-- 当前徽章状态 -->
          <div class="mb-6 p-4 bg-gray-900 rounded-lg">
            <h3 class="text-lg font-semibold text-white mb-3">当前徽章状态</h3>
            <div class="flex items-center gap-4">
              <div class="flex items-center">
                <span class="text-gray-400">状态:</span>
                <span :class="badgeCount > 0 ? 'text-green-400' : 'text-gray-400'" class="ml-2 font-semibold">
                  {{ badgeCount > 0 ? '已设置' : '未设置' }}
                </span>
              </div>
              <div v-if="badgeCount > 0" class="flex items-center">
                <span class="text-gray-400">数量:</span>
                <span class="text-tech-accent ml-2 font-bold text-lg">{{ badgeCount }}</span>
              </div>
            </div>
          </div>

          <!-- 快速操作按钮 -->
          <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <button
              @click="setBadge(1)"
              :disabled="!isSupported"
              class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i class="i-carbon-notification mr-2"></i>
              设置为 1
            </button>
            
            <button
              @click="setBadge(5)"
              :disabled="!isSupported"
              class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-4 py-3 rounded-lg transition-colors"
            >
              <i class="i-carbon-email mr-2"></i>
              设置为 5
            </button>
            
            <button
              @click="setBadge(99)"
              :disabled="!isSupported"
              class="bg-orange-600 hover:bg-orange-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-4 py-3 rounded-lg transition-colors"
            >
              <i class="i-carbon-warning mr-2"></i>
              设置为 99
            </button>
            
            <button
              @click="clearBadge"
              :disabled="!isSupported"
              class="bg-red-600 hover:bg-red-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-4 py-3 rounded-lg transition-colors"
            >
              <i class="i-carbon-clean mr-2"></i>
              清除徽章
            </button>
          </div>

          <!-- 自定义徽章数量 -->
          <div class="mb-6">
            <label class="block text-gray-300 mb-3">自定义徽章数量:</label>
            <div class="flex gap-3">
              <input
                v-model.number="customBadgeCount"
                type="number"
                min="0"
                max="999"
                placeholder="输入数字 (0-999)"
                class="flex-1 bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2"
              >
              <button
                @click="setBadge(customBadgeCount)"
                :disabled="!isSupported || !isValidBadgeCount"
                class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <i class="i-carbon-checkmark mr-2"></i>
                设置徽章
              </button>
            </div>
            <p class="text-gray-400 text-sm mt-2">
              输入 0 将清除徽章，输入正数将设置对应的徽章数量
            </p>
          </div>
        </div>
      </div>

      <!-- 模拟场景演示 -->
      <div class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-6 text-white">模拟应用场景</h3>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- 邮件应用场景 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h4 class="text-lg font-semibold text-white mb-4 flex items-center">
              <i class="i-carbon-email text-blue-400 mr-3"></i>
              邮件应用
            </h4>
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <span class="text-gray-300">未读邮件:</span>
                <span class="text-white font-semibold">{{ emailCount }} 封</span>
              </div>
              <div class="flex gap-2">
                <button
                  @click="simulateNewEmail"
                  class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <i class="i-carbon-add mr-1"></i>
                  新邮件
                </button>
                <button
                  @click="simulateReadEmail"
                  :disabled="emailCount === 0"
                  class="bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <i class="i-carbon-view mr-1"></i>
                  已读
                </button>
              </div>
            </div>
          </div>

          <!-- 聊天应用场景 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h4 class="text-lg font-semibold text-white mb-4 flex items-center">
              <i class="i-carbon-chat text-green-400 mr-3"></i>
              聊天应用
            </h4>
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <span class="text-gray-300">未读消息:</span>
                <span class="text-white font-semibold">{{ chatCount }} 条</span>
              </div>
              <div class="flex gap-2">
                <button
                  @click="simulateNewMessage"
                  class="bg-green-600 hover:bg-green-700 text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <i class="i-carbon-add mr-1"></i>
                  新消息
                </button>
                <button
                  @click="simulateReadMessage"
                  :disabled="chatCount === 0"
                  class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <i class="i-carbon-checkmark mr-1"></i>
                  已读
                </button>
              </div>
            </div>
          </div>

          <!-- 任务管理场景 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h4 class="text-lg font-semibold text-white mb-4 flex items-center">
              <i class="i-carbon-task text-orange-400 mr-3"></i>
              任务管理
            </h4>
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <span class="text-gray-300">待办任务:</span>
                <span class="text-white font-semibold">{{ taskCount }} 个</span>
              </div>
              <div class="flex gap-2">
                <button
                  @click="simulateNewTask"
                  class="bg-orange-600 hover:bg-orange-700 text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <i class="i-carbon-add mr-1"></i>
                  新任务
                </button>
                <button
                  @click="simulateCompleteTask"
                  :disabled="taskCount === 0"
                  class="bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <i class="i-carbon-checkmark mr-1"></i>
                  完成
                </button>
              </div>
            </div>
          </div>

          <!-- 社交应用场景 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h4 class="text-lg font-semibold text-white mb-4 flex items-center">
              <i class="i-carbon-user-multiple text-purple-400 mr-3"></i>
              社交应用
            </h4>
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <span class="text-gray-300">新通知:</span>
                <span class="text-white font-semibold">{{ socialCount }} 个</span>
              </div>
              <div class="flex gap-2">
                <button
                  @click="simulateNewNotification"
                  class="bg-purple-600 hover:bg-purple-700 text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <i class="i-carbon-add mr-1"></i>
                  新通知
                </button>
                <button
                  @click="simulateReadNotification"
                  :disabled="socialCount === 0"
                  class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-3 py-2 rounded text-sm transition-colors"
                >
                  <i class="i-carbon-view mr-1"></i>
                  查看
                </button>
              </div>
            </div>
          </div>
        </div>

        <div class="mt-6 p-4 bg-blue-900/30 border border-blue-600 rounded-lg">
          <p class="text-blue-400 text-sm">
            <i class="i-carbon-information mr-2"></i>
            以上场景会自动更新应用徽章数量，模拟真实应用的使用体验
          </p>
        </div>
      </div>

      <!-- 徽章历史记录 -->
      <div v-if="badgeHistory.length > 0" class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-4 text-white">徽章操作历史</h3>
        
        <div class="space-y-2 max-h-48 overflow-y-auto">
          <div
            v-for="(record, index) in badgeHistory.slice().reverse()"
            :key="index"
            class="bg-gray-800 rounded-lg p-3 flex justify-between items-center"
          >
            <div>
              <span class="text-white font-medium">{{ record.action }}</span>
              <span v-if="record.count !== null" class="text-tech-accent ml-2">{{ record.count }}</span>
            </div>
            <span class="text-gray-400 text-sm">{{ formatTime(record.timestamp) }}</span>
          </div>
        </div>
        
        <div class="mt-4 pt-4 border-t border-gray-700">
          <button
            @click="clearHistory"
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
          >
            <i class="i-carbon-trash-can mr-1"></i>
            清空历史
          </button>
        </div>
      </div>

      <!-- 错误信息 -->
      <div v-if="error" class="tech-card border-red-600 mb-8">
        <div class="flex items-center mb-2">
          <i class="i-carbon-warning text-red-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-red-500">错误</h3>
        </div>
        <p class="text-gray-300">{{ error }}</p>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 81+, Edge 81+ (主要在PWA中使用)</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要方法</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.setAppBadge(count)</code> - 设置徽章数量</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.setAppBadge()</code> - 显示空徽章</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.clearAppBadge()</code> - 清除徽章</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>邮件应用显示未读邮件数量</li>
              <li>聊天应用显示未读消息数量</li>
              <li>任务管理应用显示待办事项</li>
              <li>社交应用显示新通知数量</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用要求</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>主要在PWA（渐进式Web应用）中使用</li>
              <li>应用需要被安装到桌面或主屏幕</li>
              <li>需要在安全上下文（HTTPS）中使用</li>
              <li>徽章数量通常限制在999以内</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// 类型定义
interface BadgeRecord {
  action: string
  count: number | null
  timestamp: number
}

// 响应式状态
const isSupported = ref(false)
const badgeCount = ref(0)
const customBadgeCount = ref<number>(0)
const error = ref('')
const badgeHistory = ref<BadgeRecord[]>([])

// 模拟应用场景的计数器
const emailCount = ref(0)
const chatCount = ref(0)
const taskCount = ref(0)
const socialCount = ref(0)

// 计算属性
const isValidBadgeCount = computed(() => 
  typeof customBadgeCount.value === 'number' && 
  customBadgeCount.value >= 0 && 
  customBadgeCount.value <= 999
)

const totalNotifications = computed(() => 
  emailCount.value + chatCount.value + taskCount.value + socialCount.value
)

// 初始化
onMounted(() => {
  checkSupport()
})

// 检查浏览器支持
const checkSupport = () => {
  isSupported.value = !!(
    'setAppBadge' in navigator && 
    'clearAppBadge' in navigator
  )
}

// 设置徽章
const setBadge = async (count?: number) => {
  try {
    error.value = ''
    
    if (!isSupported.value) {
      throw new Error('当前浏览器不支持 Badging API')
    }

    if (count === undefined || count === 0) {
      await navigator.clearAppBadge()
      badgeCount.value = 0
      addToHistory('清除徽章', null)
    } else {
      await navigator.setAppBadge(count)
      badgeCount.value = count
      addToHistory('设置徽章', count)
    }
  } catch (err) {
    console.error('设置徽章失败:', err)
    error.value = err instanceof Error ? err.message : '设置徽章失败'
  }
}

// 清除徽章
const clearBadge = async () => {
  await setBadge(0)
}

// 更新总徽章数量
const updateTotalBadge = async () => {
  const total = totalNotifications.value
  await setBadge(total)
}

// 邮件场景模拟
const simulateNewEmail = async () => {
  emailCount.value++
  await updateTotalBadge()
}

const simulateReadEmail = async () => {
  if (emailCount.value > 0) {
    emailCount.value--
    await updateTotalBadge()
  }
}

// 聊天场景模拟
const simulateNewMessage = async () => {
  chatCount.value++
  await updateTotalBadge()
}

const simulateReadMessage = async () => {
  if (chatCount.value > 0) {
    chatCount.value--
    await updateTotalBadge()
  }
}

// 任务场景模拟
const simulateNewTask = async () => {
  taskCount.value++
  await updateTotalBadge()
}

const simulateCompleteTask = async () => {
  if (taskCount.value > 0) {
    taskCount.value--
    await updateTotalBadge()
  }
}

// 社交场景模拟
const simulateNewNotification = async () => {
  socialCount.value++
  await updateTotalBadge()
}

const simulateReadNotification = async () => {
  if (socialCount.value > 0) {
    socialCount.value--
    await updateTotalBadge()
  }
}

// 添加到历史记录
const addToHistory = (action: string, count: number | null) => {
  badgeHistory.value.push({
    action,
    count,
    timestamp: Date.now()
  })
  
  // 只保留最近20条记录
  if (badgeHistory.value.length > 20) {
    badgeHistory.value.splice(0, badgeHistory.value.length - 20)
  }
}

// 清空历史记录
const clearHistory = () => {
  badgeHistory.value = []
}

// 格式化时间
const formatTime = (timestamp: number): string => {
  return new Date(timestamp).toLocaleTimeString('zh-CN')
}
</script>
